package com.hmall.order.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmall.common.client.feignClient;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.IOrderServiceDetail;
import com.hmall.order.service.impl.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    OrderService orderService;
    @Autowired
    private feignClient client;
    @Autowired
    private IOrderServiceDetail detail;
    @Scheduled(cron = "*/60 * * * * ?")
    public void handleOrderTimeOut(){
        log.info("订单超时任务启动....");
        Date date = new Date(System.currentTimeMillis() ); //- 30 * 60 * 1000
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getStatus,1);
        queryWrapper.le(Order::getCreateTime,date);
        List<Order> list = orderService.list(queryWrapper);
        for (Order order : list) {
            order.setStatus(5);
            orderService.updateById(order);
            LambdaQueryWrapper<OrderDetail> DetailQuery = new LambdaQueryWrapper<>();
            DetailQuery.eq(OrderDetail::getOrderId,order.getId());
            List<OrderDetail> details = detail.list(DetailQuery);
            for (OrderDetail orderDetail : details) {
                client.reduce(orderDetail.getItemId(),-orderDetail.getNum());
            }
        }

        log.info("订单超时任务结束....");

    }
}
